// 云函数入口文件
const cloud = require('wx-server-sdk')
const nodeExcel = require('excel-export')
const path = require('path');
cloud.init()

// 云函数入口函数
exports.main = async(event, context) => {
  var tableHead = event.excelhead;
  var tableMap = {
    styleXmlFile: path.join(__dirname, "styles.xml"),
    name: Date.now() + "-export",
    cols: [],
    rows: [],
  }

  //添加表头  此处要注意格式type，会影响到rows
  tableMap.cols = [{
    caption: tableHead[0],
    type: 'string'
  }, {
    caption: tableHead[1],
    type: 'string'
  }, {
    caption: tableHead[2],
    type: 'string'
  }, {
    caption: tableHead[3],
    type: 'string'
  }, {
    caption: tableHead[4],
    type: 'string'
  }]

  var output = event.excelbody
  //添加每一行数据 此处字段数据需根据业务需求来重新定义
  console.log(output)
  console.log(output.length)
  for (var i = 0; i < output.length; i++) {
    tableMap.rows[tableMap.rows.length] = [
      output[i].name, output[i].sex, output[i].IDcard, output[i].houseID, output[i].ioNumber
    ]
  }
  console.log(tableMap);
  //保存excelResult到相应位置
  var excelResult = nodeExcel.execute(tableMap);
  var filePath = "outputExcels";
  var fileName = Date.now() + '.xlsx';
  return await cloud.uploadFile({
    cloudPath: path.join(filePath, fileName),
    fileContent: new Buffer(excelResult, 'binary')
  });
}
